﻿using AppCommerciaux.ViewModels;
using Calendar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace AppCommerciaux.Views
{
    /// <summary>
    /// Logique d'interaction pour ConsulterRendezVousView.xaml
    /// </summary>
    public partial class ConsulterRendezVousView : UserControl
    {
        private List<Appointment> m_Appointments;
        private long identifiant_agenda = 0;

        public ConsulterRendezVousView()
        {
            InitializeComponent();        

            this.dayView1.StartDate = DateTime.Now.AddDays(-3);            
            this.dayView1.SelectionChanged += _dayView_SelectionChanged;

           m_Appointments = new List<Appointment>();
           Appointment m_Appointment;

            //TODO Allons chercher les rendez vous dans la bdd 
            using (Entity.liv3Entities1 dc = new Entity.liv3Entities1())
            {
                List<Entity.agenda> myCalendarDate = new List<Entity.agenda>();
                myCalendarDate = dc.agenda.ToList();

                //TODO Affichons les rendez vous dans le calendrier               
                foreach (var item in myCalendarDate)
                {
                    DateTime FormatDateDeb =  Convert.ToDateTime(item.date_debut);
                    DateTime FormatDateFin = Convert.ToDateTime(item.date_fin);
                    string Titre = item.infos_supp + " " + item.tiers_contact;

                    m_Appointment = new Appointment();

                    m_Appointment.StartDate = FormatDateDeb;
                    m_Appointment.EndDate = FormatDateFin; 
                    m_Appointment.Title = Titre;

                    m_Appointments.Add(m_Appointment);
                } 
            }

            //Gestionnaire d'événements
            dayView1.StartDate = DateTime.Now;
            dayView1.NewAppointment += new NewAppointmentEventHandler(dayView1_NewAppointment);
            dayView1.SelectionChanged += new EventHandler(dayView1_SelectionChanged);
            dayView1.ResolveAppointments += new Calendar.ResolveAppointmentsEventHandler(this.dayView1_ResolveAppointments);
            dayView1.MouseClick += dayView1_MouseClick;


        }

        #region "Evenement utile dans le calendar"

        //Clic gauche ou droit sur le windowformhost pour le dayviewCalendar
        private void dayView1_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
          
            try
            {
                // si c'est un clic droit, on ouvre le menu contextuel
                if (e.Button == System.Windows.Forms.MouseButtons.Right)
                {
                    Appointment m_App = new Appointment();
                    m_App = dayView1.SelectedAppointment;
                    if (m_App != null)
                    {
                        NewRdvCm.IsEnabled = false;
                        myWFH.ContextMenu.IsOpen = true;
                       
                    }
                    else
                    {
                        NewRdvCm.IsEnabled = true;
                        myWFH.ContextMenu.IsOpen = true; 
                    }
                
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        // Nouveau Rdv
        void NewRdvCm_Click(object sender, EventArgs args)
        {
            try
            {
                DateTime dateDeb = dayView1.SelectionStart;
                DateTime dateFin = dayView1.SelectionEnd;
                string title = "Ecrivez ici un commentaire";
                NewRdvCm_Click(sender, args, dateDeb, dateFin, title);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void NewRdvCm_Click(object sender, EventArgs args, DateTime dateDeb, DateTime dateFin, string myTitle)
        {
            //TODO appel d'une "Page" qui va renseigner date debut, fin, commentaire, id contact qui sera dans une liste de contact
            try
            {
                AppCommerciaux.Views.GestionnaireDeRendezVousView myPage = new GestionnaireDeRendezVousView(dateDeb, dateFin, myTitle, this);
                myPage.Show();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //Modifier un Rdv
        void EditRdvCm_Click(object sender, EventArgs args)
        {
            //TODO appel de cette page avec l'id du rdv pour charger la page
            try
            {
                
                Appointment m_App = new Appointment();
                m_App = dayView1.SelectedAppointment;
                string FormatDateDeb = m_App.StartDate.ToString();
                string FormatDateFin = m_App.EndDate.ToString();


                // Recuperation de l'identifiant du rdv
                using (Entity.liv3Entities1 dc = new Entity.liv3Entities1())
                {
                    Entity.agenda myAgenda = dc.agenda.Where(a => a.date_debut == FormatDateDeb && a.date_fin == FormatDateFin).FirstOrDefault();

                    if (myAgenda != null)
                    {
                        //identifiant_agenda = myAgenda.id;
                        AppCommerciaux.Views.GestionnaireDeRendezVousView myPage = new GestionnaireDeRendezVousView(myAgenda, this);
                        myPage.Show();
                    }                    
                }             
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //Supprimer un Rdv
        void DeleteRdvCm_Click(object sender, EventArgs args)
        {
            try
            {
                if (MessageBox.Show("Êtes-vous de vouloir supprimer ce rendez-vous ? ", "Suppression définitive du rendez-vous", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                { 
                    //MessageBox.Show("Clicked Delete!");
                    Appointment m_App = new Appointment();
                    m_App = dayView1.SelectedAppointment;
                    m_Appointments.Remove(m_App);
                    dayView1.Invalidate();

                    //TODO suppression du rendez vous en bdd
                    string FormatDateDeb = m_App.StartDate.ToString();
                    string FormatDateFin = m_App.EndDate.ToString();
                    // Recuperation de l'identifiant du rdv
                    using (Entity.liv3Entities1 dc = new Entity.liv3Entities1())
                    {
                        Entity.agenda myAgenda = dc.agenda.Where(a => a.date_debut == FormatDateDeb && a.date_fin == FormatDateFin).FirstOrDefault();

                        if (myAgenda != null)
                        {
                            identifiant_agenda = myAgenda.id;
                            Entity.agenda myAppointmentToDelete = dc.agenda.Where(d => d.id == identifiant_agenda).FirstOrDefault();
                            dc.agenda.Remove(myAppointmentToDelete);
                            dc.SaveChanges();
                        }
                    }

                    MessageBox.Show("Suppression du rendez-vous réussi", "Suppression", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {                
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region "Autres Evenement de calendar"

        void _dayView_SelectionChanged(object sender, EventArgs e)
        {
            //-> Action à faire : lorsqu'on clique sur un RDV, afficher le détail
            Appointment myAppointment = new Appointment();
            myAppointment = this.dayView1.SelectedAppointment;
        }

        private void calAgenda_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
        {
            DateTime SelectionDate = (DateTime)calAgenda.SelectedDate;
            this.dayView1.StartDate = SelectionDate.AddDays(-3);
        }

        void dayView1_NewAppointment(object sender, NewAppointmentEventArgs args)
        {
            //Appel de l'evenement click du menu contextuel
            NewRdvCm_Click(sender, args, args.StartDate,args.EndDate,args.Title);
        }

        private void dayView1_SelectionChanged(object sender, EventArgs e)
        {
            //MessageBox.Show(_dayView.SelectionStart.ToString() + ":" + _dayView.SelectionEnd.ToString());
        }

        private void dayView1_ResolveAppointments(object sender, ResolveAppointmentsEventArgs args)
        {
            List<Appointment> m_Apps = new List<Appointment>();

            foreach (Appointment m_App in m_Appointments)
                if ((m_App.StartDate >= args.StartDate) &&
                    (m_App.StartDate <= args.EndDate))
                    m_Apps.Add(m_App);

            args.Appointments = m_Apps;
        }
        #endregion

        private void ButtonRafraichirCalendar_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                dayView1.Invalidate();

                m_Appointments = new List<Appointment>();
                Appointment m_Appointment;

                //TODO Rafraichir le calendrier
                using (Entity.liv3Entities1 dc = new Entity.liv3Entities1())
                {
                    List<Entity.agenda> myCalendarDate = new List<Entity.agenda>();
                    myCalendarDate = dc.agenda.ToList();

                    //TODO Affichons les rendez vous dans le calendrier               
                    foreach (var item in myCalendarDate)
                    {
                        DateTime FormatDateDeb = Convert.ToDateTime(item.date_debut);
                        DateTime FormatDateFin = Convert.ToDateTime(item.date_fin);
                        string Titre = item.infos_supp + " " + item.tiers_contact;

                        m_Appointment = new Appointment();

                        m_Appointment.StartDate = FormatDateDeb;
                        m_Appointment.EndDate = FormatDateFin;
                        m_Appointment.Title = Titre;

                        m_Appointments.Add(m_Appointment);
                    }
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


    }
}
